<template>
  <div id="systemMessagePage">
    <!-- 使用面包屑组件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <TableFilter :config="filterConfig" @search="handleSearch" />

    <div class="data-box">
      <a-table :columns="columns" :data-source="tableData" :pagination="pagination" :loading="loading">
        <!-- 表格头部 -->
        <template #headerCell="{ column }">
          <!-- 根据表头字段进行表头修饰 -->
        </template>

        <!-- 表格内容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根据不同的列显示不同的内容修饰 -->
          <template v-if="column.dataIndex === 'content'">
            {{ record.content.length > 10 ? record.content.slice(0, 10) + '...' : record.content }}
          </template>
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="record.type === 1 ? 'blue' : 'green'">
              {{ record.type === 1 ? '任务消息' : '通知消息' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'messageStatus'">
            <a-tag :bordered="false" color="processing" v-if="record.messageStatus == 0">待处理</a-tag>
            <a-tag :bordered="false" color="success" v-else-if="record.messageStatus == 1">已处理</a-tag>
            <a-tag :bordered="false" color="success" v-else>已发送无需处理</a-tag>
          </template>
          <template v-if="column.dataIndex === 'handler'"> {{ record.handler ?? '' }} </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleView(record)">查看</a-button>

            <a-button @click="handleEdit(record)" v-if="record.messageStatus == 0">修改</a-button>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 消息处理 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        消息处理
        <a-tag color="warning"><template #icon>
            <ExclamationCircleOutlined />
          </template> ID: {{ editFormData.id }}</a-tag>
      </template>
      <DynamicForm ref="editFormRef" :fieldConfig="editFieldConfig" @submit="handleEditSubmit"
        :formData="editFormData" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import BreadcrumbComponent from '@/components/BreadcrumbComponent.vue'
import TableFilter from '@/components/TableFilter.vue'
import DynamicForm from '@/components/DynamicForm.vue'
import { tableColumns, filterFields, getEditFieldConfig } from '@/models/systemMessage'
import { createPagination } from '@/utils/pagination'
import { systemMessageApi } from '@/api'
import { useRouter, useRoute } from 'vue-router'
import { watchRouteQuery } from '@/utils/routeQueryWatcherUtil'

/*******定义参数部分*****************************/
const breadcrumbItems = [{ url: '', name: '系统消息' }]
const columns = tableColumns
const filterConfig = filterFields
const editFieldConfig = ref<Record<string, any>>({})
const router = useRouter()
const route = useRoute()

const loading = ref(false)

// 分页配置
const pagination = createPagination()

// 数据
const tableData = ref([])
const editRecordId = ref<number>(0) // 当前编辑的用户ID
const editFormData = reactive<any>({}) // 当前编辑的用户数据
/*******数据获取与初始化部分*****************************/

// 获取数据
const fetchData = async (params?: any) => {
  try {
    loading.value = true // 开始加载
    const {
      data: { list, page, limit, total },
    } = await systemMessageApi.getSystemMessageList(params)
    tableData.value = list || []
    pagination.updatePagination(page, limit, total)
  } catch (error) {
    console.error('获取系统消息列表失败', error)
  } finally {
    loading.value = false // 加载完成
  }
}

// 监听路由变化,更新列表数据
watchRouteQuery(fetchData)

/*******操作方法部分部分*****************************/
// 搜索
const handleSearch = (params: any) => {
  router.push({ query: params })
}

// 处理修改操作
const showModalEdit = ref(false)
const handleEdit = (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig()
  }
  editRecordId.value = Number(record.id)
  Object.assign(editFormData, record)
  showModalEdit.value = true
}

const editFormRef = ref()
const handleEditSubmit = async (data: any) => {
  try {
    await systemMessageApi.updateSystemMessage(editRecordId.value, data)
    message.success('修改成功')
    showModalEdit.value = false
    fetchData(route.query)
  } catch (error) {
    console.error('修改失败', error)
  } finally {
    editFormRef.value?.resetLoading()
  }
}

// 查看
const handleView = (record: any) => {
  router.push({ name: 'SystemMessageDetail', params: { id: record.id } })
}
</script>

<style scoped></style>
